<?php

namespace app\distribution\controller\sys_admin;

use app\AdminController;
use app\member\model\{UsersLevelApplyModel, UsersModel};
use app\distribution\model\DividendRoleModel;
use think\Db;

/**
 * 游客等级管理
 */
class LevelApply extends AdminController
{
    //*------------------------------------------------------ */
    //-- 初始化
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new UsersLevelApplyModel();
    }
    /*------------------------------------------------------ */
    //--首页
    /*------------------------------------------------------ */
    public function index()
    {
        $this->getList(true);
        return $this->fetch('index');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false)
    {
        $this->sqlOrder = 'level ASC';
        // $this->sort_by = 'ASC';
        $data = $this->getPageList($this->Model);
        $this->assign("data", $data);
        if ($runData == false) {
            $data['content'] = $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('', '', $data);
        }
        return true;
    }

    public function asInfo($data)
    {
        $list = (new DividendRoleModel)->getRows();
        $this->assign("userRole", arrToSel($list, $data['own_level']));
        $this->assign("userRole2", arrToSel($list, $data['push_level']));
        $data['value'] = json_decode($data['value'], true);
        return $data;
    }

    /*------------------------------------------------------ */
    //-- 添加前处理
    /*------------------------------------------------------ */
    public function beforeAdd($data)
    {
        if (empty($data['jc_name'])) return $this->error('操作失败:奖金池称不能为空！');
        $count = $this->Model->where('jc_name', $data['jc_name'])->count('level_id');
        if ($count > 0) return $this->error('操作失败:已存在相同的奖金池名称，不允许重复添加！');

        return $data;
    }
    /*------------------------------------------------------ */
    //-- 添加后处理
    /*------------------------------------------------------ */
    public function afterAdd($data)
    {
        $this->_Log($data['level_id'], '添加游客等级:' . $data['level_name']);
    }
    /*------------------------------------------------------ */
    //-- 修改前处理
    /*------------------------------------------------------ */
    public function beforeEdit($data)
    {


        if (empty($data['jc_name'])) return $this->error('操作失败:奖金池称不能为空！');

        return $data;
    }
    /*------------------------------------------------------ */
    //-- 修改后处理
    /*------------------------------------------------------ */
    public function afterEdit($data)
    {

        $this->_Log($data['role_id'], '修改奖金:' . $data['jc_name']);
    }
    /*------------------------------------------------------ */
    //-- 删除等级
    /*------------------------------------------------------ */
    public function delete()
    {
        $level_id = input('level_id', 0, 'intval');
        if ($level_id < 1) return $this->error('传参失败！');
        $res = $this->Model->where('level_id', $level_id)->delete();
        if ($res < 1) return $this->error('未知错误，删除失败！');
        $this->Model->cleanMemcache();
        return $this->success('删除成功！', url('index'));
    }

    // 代理列表
    public function agent_list()
    {
        $this->getAgentList(true);
        return $this->fetch('agent');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getAgentList($runData = false)
    {
        $LevelList = (new UsersLevelModel)->getRows();

        $search['level_id'] = input('level_id', 0, 'intval');
        $search['keyword'] = input('keyword', '', 'trim');
        $where = [];
        if ($search['level_id'] > 0) {
            $where[] = ['level_id', '=', $search['level_id']];
        }
        if (empty($search['keyword']) == false) {
            if (is_numeric($search['keyword']) && strlen($search['keyword']) == 5) {
                $user_ids = UsersModel::where('user_id', $search['keyword'])->column('user_id');
            } else {
                $user_ids = UsersModel::where([['mobile|nick_name', 'like', "%" . $search['keyword'] . "%"]])->column('user_id');
            }
            $where[] = ['user_id', 'in', $user_ids];
        }

        $this->assign("LevelList", $LevelList);
        $data = $this->getPageList(new UsersLevelAgentModel, $where);
        $this->assign("data", $data);
        if ($runData == false) {
            $data['content'] = $this->fetch('agent_list')->getContent();
            unset($data['list']);
            return $this->success('', '', $data);
        }
        return true;
    }

    /**
     * [agent_apply 代理申请列表]
     */
    public function agent_apply()
    {
        $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getApplyList(true);
        return $this->fetch('apply');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getApplyList($runData = false)
    {
        $this->assign('status', [0 => '待审核', 1 => '<font color="green">已通过</font>', 2 => '<font color="red">未通过</font>']);
        $LevelList = (new UsersLevelModel)->getRows();
        $this->assign("LevelList", $LevelList);

        $reportrange = input('reportrange');
        $where = [];
        if (empty($reportrange) == false) {
            $dtime = explode('-', $reportrange);
            $where[] = ['add_time', 'between', [strtotime($dtime[0]), strtotime($dtime[1]) + 86399]];
        } else {
            $where[] = ['add_time', 'between', [strtotime("-1 months"), time()]];
        }

        $search['level_id'] = input('level_id', 0, 'intval');
        $search['keyword'] = input('keyword', '', 'trim');
        $search['status'] = input('status', 0, 'trim');
        $where = [];
        if ($search['level_id'] > 0) {
            $where[] = ['level_id', '=', $search['level_id']];
        }
        if (empty($search['keyword']) == false) {
            if (is_numeric($search['keyword']) && strlen($search['keyword']) == 5) {
                $user_ids = UsersModel::where('user_id', $search['keyword'])->column('user_id');
            } else {
                $user_ids = UsersModel::where([['mobile|nick_name', 'like', "%" . $search['keyword'] . "%"]])->column('user_id');
            }
            $where[] = ['user_id', 'in', $user_ids];
        }

        if ($search['status'] >= 0) {
            $where[] = ['status', '=', $search['status']];
        }

        $data = $this->getPageList(new UsersAgentApplyModel, $where);
        $this->assign("data", $data);
        if ($runData == false) {
            $data['content'] = $this->fetch('apply_list')->getContent();
            unset($data['list']);
            return $this->success('', '', $data);
        }
        return true;
    }

    /**
     * [applyInfo 申请详情]
     */
    public function applyInfo()
    {
        $id = input('id', 0, 'intval');
        $LevelList = (new UsersLevelModel)->getRows();
        $this->assign("LevelList", $LevelList);
        $applyInfo = UsersAgentApplyModel::find($id);
        $this->assign('status', [0 => '待审核', 1 => '<font color="green">已通过</font>', 2 => '<font color="red">未通过</font>']);
        $this->assign("row", $applyInfo);
        return $this->fetch('apply_info');
    }

    /**
     * [applyInfo 操作申请]
     */
    public function saveApply()
    {
        $operating = input('operating', 'note', 'trim');
        $remarks = input('remarks', '', 'trim');

        $id = input('id', 0, 'intval');
        $applyInfo = UsersAgentApplyModel::find($id);
        if (empty($applyInfo)) return $this->error();
        $applyInfo->remarks = $remarks;
        Db::startTrans();
        if ($operating == 'refuse') {
            if (empty($remarks)) return $this->error('拒绝申请请输入备注.');
            if ($applyInfo->status != 0) return $this->error('当前状态不能拒绝申请.');
            $applyInfo->status = 2;
        } else if ($operating == 'success') {
            if ($applyInfo->status != 0) return $this->error('当前状态不能通过申请.');
            $applyInfo->status = 1;
            $levelInfo = (new \app\member\model\UsersLevelModel)->getRows()[$applyInfo->level_id];
            $awhere[] = ['province', '=', $applyInfo->province];
            $awhere[] = ['level_id', '=', $levelInfo['level_id']];
            $errorText = '该省份已有代理';
            if ($levelInfo['identification'] == 'street_agent') {
                $awhere[] = ['district', '=', $applyInfo->district];
                $awhere[] = ['city', '=', $applyInfo->city];
                $awhere[] = ['street', '=', $applyInfo->street];
                $errorText = '该街道/乡镇已有代理';
            } elseif ($levelInfo['identification'] == 'district_agent') {
                $awhere[] = ['district', '=', $applyInfo->district];
                $awhere[] = ['city', '=', $applyInfo->city];
                $errorText = '该区域已有代理';
            } elseif ($levelInfo['identification'] == 'city_agent') {
                $awhere[] = ['city', '=', $applyInfo->city];
                $errorText = '该城市已有代理';
            }

            $UsersLevelAgentModel = new \app\member\model\UsersLevelAgentModel();
            $count = $UsersLevelAgentModel->where($awhere)->count();
            if ($count > 0) return $this->error($errorText);
            $UsersModel = new UsersModel();
            $userInfo = $UsersModel->info($applyInfo->user_id);
            $inArr['province'] = $applyInfo->province;
            $inArr['city'] = $applyInfo->city;
            $inArr['district'] = $applyInfo->district;
            $inArr['street'] = $applyInfo->street;
            $inArr['level_id'] = $applyInfo->level_id;
            $inArr['user_id'] = $userInfo['user_id'];
            $inArr['merger_name'] = $applyInfo->merger_name;
            $res = $UsersLevelAgentModel->save($inArr);
            if ($res <= 0) {
                Db::rollback();
                return $this->error('操作失败.-1');
            }

            if (empty($userInfo[$levelInfo['identification']])) {
                $res = $UsersModel->where('user_id', $userInfo['user_id'])->update([$levelInfo['identification'] => $levelInfo['level_id']]);
                if ($res < 1) {
                    Db::rollback();
                    return $this->error('操作失败.-2');
                }
                $UsersModel->cleanMemcache($userInfo['user_id']);
            }
        }
        $res = $applyInfo->save();
        if ($res <= 0) {
            Db::rollback();
            return $this->error('操作失败.-3');
        }
        Db::commit();
        return $this->success('操作成功');
    }
}
